import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend

from apps.ausers.models import User
from apps.oauth.utils import SecretOauth


from meiduo_mall.settings.dev import logger


# 封装函数
def get_user_by_account(account):
    try:
        # 新增 手机号校验
        if re.match(r'^1[345789]\d{9}$', account):

            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)

    except Exception as e:
        logger.error(e)
        return None
    else:
        return user



class UsernameMobileAuthBackend(ModelBackend):

    # 重写函数
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 接收账户

        user = get_user_by_account(username)
        # 校验密码是否正确
        if user and user.check_password(password):
            return user



def check_verify_email_token(token):
    """
    验证token并提取user
    :param token: 用户信息签名后的结果
    :return: user, None
    """

    try:
        token_dict = SecretOauth().loads(token)
    except Exception as e:
        logger.error(e)
        return None

    try:
        user = User.objects.get(id=token_dict['user_id'], email=token_dict['email'])
    except Exception as e:
        logger.error(e)
        return None
    else:
        return user


def generate_verify_email_url(user):
    """
    :param user: 用户对象
    :return:
    """
    # 1.加密的数据
    data_dict = {'user_id': user.id, "email": user.email}

    # 2. 进行加密数据

    secret_data = SecretOauth().dumps(data_dict)

    # 3. 返回拼接url
    active_url = settings.EMAIL_ACTIVE_URL + '?token=' + secret_data
    return active_url
